package com.click369.crm.controller;

import java.util.HashSet;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.click369.crm.pojo.CStaff;
import com.click369.crm.service.StaffService;

public class CRMRealm extends AuthorizingRealm{
	
	@Autowired
	private StaffService staffService;
	
	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		CStaff staff=(CStaff)principals.getPrimaryPrincipal();
		String username = staff.getUsername();
		HashSet funs = staffService.getFunctionCodeByUsername(username);
		HashSet roles = staffService.getRoleCodeByUsername(username);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setRoles(roles);
		info.setStringPermissions(funs);
		return info;
	}
	
	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken t = (UsernamePasswordToken)token;
		String username = t.getUsername();
		System.out.println("username===="+username);
		char[] password = t.getPassword();
		CStaff staff= staffService.getStaffByUsernameAndPassword(username, new String(password));
		if(null == staff){
			throw new AuthenticationException("用户名或密码不正确！");
		}
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(staff,password,staff.getName());
		return info;
	}

}
